package com.example.pei.ithinklearnt.view.activity;


import android.app.Activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;

import android.graphics.BitmapFactory;
import android.graphics.Color;

import android.os.Build;
import android.support.annotation.NonNull;

import android.support.annotation.RequiresApi;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;

import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.present.RegisterTwoPresent;
import com.example.pei.ithinklearnt.present.RegisterTwoPresentImp;
import com.example.pei.ithinklearnt.view.base.RegisterBaseActivity;
import com.example.pei.ithinklearnt.view.customview.headChooseDialog;
import com.example.pei.ithinklearnt.view.interfaces.RegisterTwoInterface;
import com.makeramen.roundedimageview.RoundedImageView;

import java.io.File;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;

import static com.example.pei.ithinklearnt.utils.ImageLoaderUtil.displayImage;
import static com.example.pei.ithinklearnt.utils.ImageLoaderUtil.getPhotoImageOption;
import static com.example.pei.ithinklearnt.utils.MyUtils.getAge;
import static com.example.pei.ithinklearnt.utils.MyUtils.isAllSpace;


public class RegisterTwoActivity extends RegisterBaseActivity implements RegisterTwoInterface,View.OnClickListener ,RadioGroup.OnCheckedChangeListener{


    private RegisterTwoPresent registerTwoPresent;

    private Button button_submit;
    private RoundedImageView roundImageHead; //压缩后的圆形头像

    private RadioButton radioButton_female;
    private RadioButton radioButton_male;

    private ProgressBar progressBar_register;


    private NumberPicker yearNumberPicker;
    private NumberPicker monthNumberPicker;
    private NumberPicker dateNumberPicker;



    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int CROP_REQUEST_CODE = 3;

    private EditText editUsername;
    private headChooseDialog dialog;

    private String phone;
    private String userName;
    private String passWord;
    private int sex;//0女 1男

    private int birthYear;
    private int birthMonth;
    private int birthDate;
    private int age;


    private TextView textView_birth;

    private boolean falgHead; //如果头像已经选择了
    private boolean flagSex;
    private boolean flagBirth;
    private boolean flagUsername; //如果昵称合法


    @BindView(R.id.tv_what)
    TextView tvWhat;

    @OnClick(R.id.btn_back)
    void back(){
        finish();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_two);
        registerTwoPresent =new RegisterTwoPresentImp(this);
        initData();
        findWidgets();


        //权限适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            registerTwoPresent.achieveAllPermissions(this,ALL);
        }
    }

    //初始化一些数据,如果是修改个人信息的话
    private void init(){
        UserInfo u= AppApplication.getCurrentUser();
        //导航和按钮文字
        tvWhat.setText("修改个人信息");
        button_submit.setText("保   存");
        button_submit.setBackgroundColor(Color.parseColor("#0D9BCD"));
        //设置头像
        String headPath=getExternalCacheDir()+"/head-"+u.getUsername()+".jpg";
        File headfile=new File(headPath);
        roundImageHead.setBackground(null);
        if(!headfile.exists()){
            displayImage(this, roundImageHead, u.getHeadFileUrl(), getPhotoImageOption());
        }else {
            //本地存在头像文件，直接使用
            Bitmap bitmap = BitmapFactory.decodeFile(headPath);
            roundImageHead.setImageBitmap(bitmap);
        }
        //初始化昵称
        editUsername.setText(u.getNickName());
        flagUsername = !isAllSpace(u.getNickName());  //判断昵称是否合法
        //初始化性别
        if(u.getSex()==1){
            radioButton_male.setChecked(true);
            radioButton_female.setChecked(false);
        }else{
            radioButton_male.setChecked(false);
            radioButton_female.setChecked(true);
        }
        //初始化年龄
        textView_birth.setText(getResources().getString(R.string.age, com.example.pei.ithinklearnt.utils.MyUtils.getAge(u.getBirthDay())));
        age=com.example.pei.ithinklearnt.utils.MyUtils.getAge(u.getBirthDay());
        String[] s=u.getBirthDay().split("-");
        if(s.length==3){
            birthYear=Integer.valueOf(s[0]);
            birthMonth=Integer.valueOf(s[1]);
            birthDate=Integer.valueOf(s[2]);
        }

        aim=1;    //aim为1代表是修改用户
    }

    //这个活动是用来注册还是修改用户
    private int aim=0;
    @Override
    public int getAim() {
        return aim;
    }

    //如果是修改 有没有修改过信息
    private boolean hasChanged=false;

    @Override
    public boolean getHasChanged() {
        return hasChanged;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
        } else {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    registerTwoPresent.getPhotoAndCrop(data.getData(),IMAGE_REQUEST_CODE,CROP_REQUEST_CODE);

                    break;
                case CAMERA_REQUEST_CODE:
                    registerTwoPresent.getPhotoAndCrop(null,CAMERA_REQUEST_CODE,CROP_REQUEST_CODE);

                    break;
                case CROP_REQUEST_CODE:
                    registerTwoPresent.CropCallback(data);

                    break;
            }
        }
    }
    /***
     * 新增7.0权限处理
     * **/
    private final int ALL = 104;
    private final int onlyWrite=103;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case ALL:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "拒绝了相关权限可能导致某些功能无法运行", Toast.LENGTH_SHORT).show();
                }
                break;
            case onlyWrite:
                if(grantResults.length>0&&grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    registerTwoPresent.openAlbum(IMAGE_REQUEST_CODE);
                }else{
                    Toast.makeText(this, "拒绝了相关权限可能导致某些功能无法运行", Toast.LENGTH_SHORT).show();
                }
                break;
        }


        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @RequiresApi(api = Build.VERSION_CODES.FROYO)
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_submit:
                registerTwoPresent.submit();     //确认注册
                break;
            case R.id.img_roudhead:                    //选择头像
                View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog, null);
                dialog = new headChooseDialog(this, R.style.transparentFrameWindowStyle,new headChooseDialog.LeaveMyDialogListener(){
                    @Override
                    public void onClick(View view) {
                        switch (view.getId()){
                            case R.id.btn_c:
                                break;
                            case R.id.btn_g: //从相册中选择头像
                               registerTwoPresent.chooseHeadFromAlbum(IMAGE_REQUEST_CODE);
                                break;
                            case R.id.btn_t: //从相机拍照
                                registerTwoPresent.chooseHeadFromCamera(CAMERA_REQUEST_CODE);
                                break;
                        }
                        dialog.dismiss();
                    }
                });
                dialog.setContentView(view, new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT));
                Window window = dialog.getWindow();
                // 设置显示动画
                assert window != null;
                window.setWindowAnimations(R.style.main_menu_animstyle);
                WindowManager.LayoutParams wl = window.getAttributes();
                wl.x = 0;
                wl.y = getWindowManager().getDefaultDisplay().getHeight();
                // 以下这两句是为了保证按钮可以水平满屏
                wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
                wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                // 设置显示位置
                dialog.onWindowAttributesChanged(wl);
                // 设置点击外围解散
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
                break;

            case R.id.btn_select_birth:         //选择生日
                CreateBirthChoice();
                break;
        }
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId==radioButton_female.getId()){
            sex=0;
          //  roundImageHead.setBackgroundResource(R.drawable.img_head);
            radioButton_female.setTextColor(Color.parseColor("#333333"));
            radioButton_male.setTextColor(Color.parseColor("#cccccc"));
        }else if (checkedId==radioButton_male.getId()){
            sex=1;
         //   roundImageHead.setBackgroundResource(R.drawable.default_male_img);
            radioButton_female.setTextColor(Color.parseColor("#cccccc"));
            radioButton_male.setTextColor(Color.parseColor("#333333"));
        }
        flagSex=true;
        if((flagUsername&&aim==1)||falgHead&&flagBirth&&flagUsername){
            button_submit.setBackgroundColor(Color.parseColor("#5CC2D9"));
            button_submit.setClickable(true);
        }else{
            button_submit.setBackgroundColor(Color.parseColor("#cccccc"));
            button_submit.setClickable(false);
        }

        hasChanged=true;
    }



    @Override
    public void setHeadBitmap(Bitmap bitmap) {
        roundImageHead.setBackground(null);
        roundImageHead.setImageBitmap(bitmap);
        //既然设置头像了
        falgHead=true;
        if((flagUsername&&aim==1)||flagSex&&flagBirth&&flagUsername){
            button_submit.setBackgroundColor(Color.parseColor("#12B7F5"));
            button_submit.setClickable(true);
        }else{
            button_submit.setBackgroundColor(Color.parseColor("#cccccc"));
            button_submit.setClickable(false);
        }

        hasChanged=true;
    }

    @Override
    public void setprogressBarVisibility(boolean enable) {
        if(enable){
            progressBar_register.setVisibility(View.VISIBLE);
        }else {
            progressBar_register.setVisibility(View.GONE);
        }
    }

    @Override
    public void setButtomSubmitClickable(boolean enable) {
        button_submit.setClickable(enable);
    }

    @Override
    public Activity getActivity() {
        return RegisterTwoActivity.this;
    }

    @Override
    public String getBirthday() {
        return birthYear+"-"+birthMonth+"-"+birthDate;
    }

    @Override
    public int getAge() {
        return age;
    }

    @Override
    public String getUserName() {
        return editUsername.getText().toString();
    }

    @Override
    public String getPassWord() {
        return passWord;
    }

    @Override
    public int getSex() {
        return sex;
    }

    @Override
    public String getPhoneNum() {
        return phone;
    }


    private void findWidgets(){

        button_submit= findViewById(R.id.btn_submit);
        roundImageHead=findViewById(R.id.img_roudhead);
        radioButton_female=findViewById(R.id.rbtn_female);
        radioButton_male=findViewById(R.id.rbtn_male);
        RadioGroup radioGroup_sex = findViewById(R.id.radioGroupID);
        textView_birth=findViewById(R.id.tv_bitrh);
        Button button_select_birth = findViewById(R.id.btn_select_birth);
        progressBar_register=findViewById(R.id.prg_register);
        editUsername=findViewById(R.id.et_nickname);

        progressBar_register.setVisibility(View.GONE); //设置不可见
        //设置监听

        //这个活动用来修改信息
        if(getIntent().getStringExtra("isModify")!=null&&getIntent().getStringExtra("isModify").equals("yes")){
            init();
        }

        button_submit.setOnClickListener(this);
        roundImageHead.setOnClickListener(this);
        radioGroup_sex.setOnCheckedChangeListener(this);
        button_select_birth.setOnClickListener(this);

        editUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(isAllSpace(s.toString())){
                    flagUsername=false;
                }else{
                    flagUsername=true;
                    if((flagUsername&&aim==1)||flagBirth&&falgHead&&flagSex){
                        button_submit.setBackgroundColor(Color.parseColor("#5CC2D9"));
                        button_submit.setClickable(true);
                    }else{
                        button_submit.setBackgroundColor(Color.parseColor("#cccccc"));
                        button_submit.setClickable(false);
                    }
                }
                hasChanged=true;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    private void initData(){
        sex=3;  //未选择
        age=200;//未选择
        falgHead=false;
        flagBirth=false;
        flagSex=false;

        birthYear=1996;
        birthMonth=11;
        birthDate=5;
        Intent intent=getIntent();
        phone=intent.getStringExtra("phoneString");
       // userName=intent.getStringExtra("userNameString");
        passWord=intent.getStringExtra("passWordString");
    }


    private boolean Leap=false;  //是否为闰年
    private Calendar c;
    private int tempBirthYear;
    private int tempBirthMonth;
    private int tempBirthDate;
    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    private void CreateBirthChoice(){
        AlertDialog.Builder builder = new AlertDialog.Builder(RegisterTwoActivity.this);
        View view = LayoutInflater.from(RegisterTwoActivity.this).inflate(R.layout.birth_choose, null);
        yearNumberPicker =  view.findViewById(R.id.year_numberpicker);
        monthNumberPicker =  view.findViewById(R.id.month_numberpicker);
        dateNumberPicker =  view.findViewById(R.id.date_numberpicker);

        yearNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        monthNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        dateNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

         c = Calendar.getInstance();
        int maxYear = c.get(Calendar.YEAR);
        final int minYear=maxYear-120;
        yearNumberPicker.setMaxValue(maxYear);
        yearNumberPicker.setMinValue(minYear);
        yearNumberPicker.setValue(birthYear);
        monthNumberPicker.setMaxValue(12);
        monthNumberPicker.setMinValue(1);
        monthNumberPicker.setValue(birthMonth);
        dateNumberPicker.setMinValue(1);
        dateNumberPicker.setMaxValue(31);
        dateNumberPicker.setValue(birthDate);
        tempBirthYear=yearNumberPicker.getValue();
        tempBirthMonth=monthNumberPicker.getValue();
        tempBirthDate=dateNumberPicker.getValue();
        birthYear=yearNumberPicker.getValue();
        birthMonth=monthNumberPicker.getValue();
        birthDate=dateNumberPicker.getValue();

        //设置监听
        yearNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                tempBirthYear=yearNumberPicker.getValue();
                if(isLeapYear(tempBirthYear)) {
                    Leap = true;
                    if(monthNumberPicker.getValue()==2){
                        dateNumberPicker.setMaxValue(29);//如果是闰年
                    }
                }
                else
                    Leap=false;
                if(monthNumberPicker.getValue()==2){
                    dateNumberPicker.setMaxValue(28);//如果不是闰年
                }
            }
        });
        //设置监听
        monthNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                tempBirthMonth=monthNumberPicker.getValue();
                switch (tempBirthMonth){
                    case 1:case 3:case 5:case 7:case 8:case 10:case 12:
                        dateNumberPicker.setMaxValue(31);
                        break;
                    case 2:
                        if(Leap) dateNumberPicker.setMaxValue(29);//如果是闰年
                        else dateNumberPicker.setMaxValue(28);//如果不是闰年
                        break;
                    case 4:case 6:case 9:case 11:
                        dateNumberPicker.setMaxValue(30);
                        break;
                }
            }
        });
        //设置监听
        dateNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                tempBirthDate=dateNumberPicker.getValue();
            }
        });
        builder.setView(view);
        builder.setPositiveButton("确定",
                new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        birthYear=tempBirthYear;
                        birthMonth=tempBirthMonth;
                        birthDate=tempBirthDate;
                        age= c.get(Calendar.YEAR)-birthYear;
                        textView_birth.setText(getResources().getString(R.string.age,age-1));
                        textView_birth.setTextColor(Color.parseColor("#333333"));
                        textView_birth.setTextSize(17);
                        flagBirth=true;
                        if((flagUsername&&aim==1)||falgHead && flagSex&&flagUsername ){
                            button_submit.setBackgroundColor(Color.parseColor("#5CC2D9"));
                            button_submit.setClickable(true);
                        }else{
                            button_submit.setBackgroundColor(Color.parseColor("#cccccc"));
                            button_submit.setClickable(false);
                        }
                        hasChanged=true;
                    }
                });
        builder.setNegativeButton("取消",
                new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        builder.create();
        builder.show();
    }

    //判断是否为闰年
    private boolean isLeapYear(int year){
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }
}
